package com.example.homework

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import com.example.homework.model.User
import com.google.android.material.bottomnavigation.BottomNavigationView

class MainActivity : AppCompatActivity(R.layout.activity_main) {

    internal val gameResultLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                val newHigh = result.data?.getIntExtra("highScore", -1) ?: -1
                if (newHigh > 0) {
                    (supportFragmentManager.findFragmentById(R.id.container) as? ProfileFragment)
                        ?.refreshHighScore(newHigh)
                }
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 第一次把“游戏”页放出来
        supportFragmentManager.beginTransaction()
            .replace(R.id.container, GameFragment())
            .commit()

        val nav = findViewById<BottomNavigationView>(R.id.bottom_nav)
        nav.setOnItemSelectedListener { item ->
            val target: Fragment = when (item.itemId) {
                R.id.nav_game    -> GameFragment()
                R.id.nav_rank    -> RankFragment()
                R.id.nav_profile -> ProfileFragment()
                else             -> return@setOnItemSelectedListener false
            }
            supportFragmentManager.beginTransaction()
                .replace(R.id.container, target)
                .commit()
            true
        }
    }
}
